<?php
namespace app\erp_meixingtiyu\controller;

use app\erp_meixingtiyu\model\TimeTemplate as TimeTemplateModel;
use app\erp_meixingtiyu\model\TimeFragment as TimeFragmentModel;
use app\store\controller\Controller as StoreController;
use think\facade\Request;
use app\erp_meixingtiyu\logic\TimeTemplate as TimeTemplateLogic;

class TimeTemplate extends StoreController
{
    // 获取所有时间段模板列表
    public function list()
    {
        $list = TimeTemplateModel::order('sort asc')->paginate(15);
        return $this->renderSuccess(compact('list'), '操作成功');
    }

    // 添加时段模板
    public function add()
    {
        $params = Request::only(['name', 'sort', 'price', 'status']);
        $template = TimeTemplateModel::create($params);
        return $this->renderSuccess(compact('template'), '添加成功');
    }

    // 编辑时段模板
    public function edit()
    {
        $params = Request::only([
            'time_template_id',
            'name',
            'sort',
            'price',
            'status',
        ]);
        $template = TimeTemplateModel::update($params);
        return $this->renderSuccess(compact('template'), '编辑成功');
    }

    /**
     * 删除指定id的时间段模板
     * @param int $timeTemplateId
     */
    public function delete($timeTemplateId)
    {
        try{
            (new TimeTemplateLogic())->deleteTemplate($timeTemplateId);
        }catch(\Exception $e) {
            return $this->renderError($e->getMessage());
        }
        return $this->renderSuccess([], '删除成功');
    }

    /**
     * 获取指定id模板的时段列表
     * @param int $timeTemplateId
     */
    public function fragments($timeTemplateId)
    {
        $fragments = TimeFragmentModel::getFragmentByTemplateId($timeTemplateId);
        return $this->renderSuccess($fragments->toArray());
    }

    /**
     * 添加时段
     * @param int $timeTemplateId
     * TODO: 时段判断，添加的时段是否和已存在的时段冲突
     */
    public function addFragment()
    {
        $params = Request::only(['time_template_id', 'start', 'end', 'sort']);
        (new TimeFragmentModel())->addFragment($params);
        
        return $this->renderSuccess([], '添加时段成功');
    }

    /**
     * 编辑时段
     * TODO: 如果未来七天内有预约该时段，则不允许修改
     * TODO: 时段判断，编辑的时段是否和已存在的时段冲突
     * @param int $timeFragmentId
     */
    public function editFragment()
    {
        $params = Request::only(['time_fragment_id', 'start', 'end', 'sort']);
        TimeFragmentModel::update($params);
        
        return $this->renderSuccess([], '编辑时段成功');
    }

    /**
     * 删除时段
     * TODO: 如果未来七天内有预约该时段，则不允许删除
     * @param int $timeFragmentId
     */
    public function delFragment()
    {
        $params = Request::only(['time_fragment_id']);
        (new TimeFragmentModel())->deleteFragment($params['time_fragment_id']);
        return $this->renderSuccess([], '删除时段成功');
    }
  
}
